// MyMouseHook.cpp: definisce le funzioni esportate per l'applicazione DLL.
//
#include "stdafx.h"

#define MYMOUSEHOOK_API extern "C" __declspec(dllexport)
#include "MyMouseHook.h"

#pragma data_seg("Shared")
static HWND hWnd = NULL;	// size of valid data block 
#pragma data_seg( )

#pragma comment(linker,"/section:Shared,rws")

HHOOK myHook = NULL;
HMODULE myInstance = NULL;

BOOL APIENTRY DllMain( HMODULE hModule,
                       DWORD  ul_reason_for_call,
                       LPVOID lpReserved
					 )
{
	switch(ul_reason_for_call)
	{
	case DLL_PROCESS_ATTACH:
		myInstance = hModule;
		break;
	case DLL_PROCESS_DETACH:
		break;
	}
    return TRUE;
}

void __stdcall Hook(HWND hwnd){
	//MessageBox(hWnd, L"ABOUT TO HOOK!", NULL, MB_OK);
	if(hWnd == NULL){
		hWnd = hwnd;
		myHook = SetWindowsHookEx(WH_MOUSE, (HOOKPROC)MyHookProcedure, myInstance, 0);
		//MessageBox(hWnd, L"HOOKED!", NULL, MB_OK);
	}
}

void __stdcall unHook(){
	if(hWnd != NULL && myHook != NULL)
	{
		UnhookWindowsHookEx(myHook);
		hWnd = NULL;
		myHook = NULL;
		//MessageBox(hWnd, L"UN-HOOKED!", NULL, MB_OK);
	}
}

LRESULT CALLBACK __stdcall MyHookProcedure(int nCode, WPARAM wParam, LPARAM lParam){
	if(nCode < 0)
		return CallNextHookEx(myHook, nCode, wParam, lParam);
	if(hWnd != NULL)
	{
		if(wParam == WM_LBUTTONDOWN || wParam == WM_NCLBUTTONDOWN)
		{
			PostMessage(hWnd, MOUSE_DOWN, 0, 0);
		}
		else if(wParam == WM_LBUTTONUP || wParam == WM_NCLBUTTONUP)
		{
			PostMessage(hWnd, MOUSE_UP, 0, 0);
		}
		//else if(wParam == WM_MOUSEMOVE)
		//	PostMessage(hWnd, MOUSE_MOVE, 0, 0);
	}
	return CallNextHookEx(myHook, nCode, wParam, lParam);
}

